//
//  BuddyListPacketProcess.m
//  HiQ
//
//  Created by shoguncao on 12-8-7.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "MainWindowController.h"
#import "BuddyListPacketProcess.h"
#import "Buddy.h"
#import "BuddyGroup.h"
#import "BuddyListSource.h"

@implementation BuddyListPacketProcess

// 接到 BuddyList 查询的回复包时的处理，做解包操作
- (void)onReceiveBuddyListPacket:(NSData *)data
{
    BUDDYLISTREPLYHRD *reply = (BUDDYLISTREPLYHRD *)[data bytes];
    
    if (reply->operation != OP_BUDDY_LIST_REPLY)    // 不是回复
        return;
    
    if (reply->error != ERR_NO_ERROR)   // 数据库查询错误
        return;
    
    NSInteger buddy_count = reply->count;
    NSInteger buddy_userid_len = reply->userid_len;
    NSInteger buddy_username_len = reply->username_len;
    NSInteger buddy_userimage_len = reply->userimage_len;
    NSInteger buddy_userstatus_len = reply->userstatus_len;
    NSInteger buddy_userlistenport_len = reply->userlistenport_len;
    NSInteger buddy_userip_len = reply->userip_len;
    
    if([data length] != buddy_userid_len+buddy_username_len+buddy_userimage_len+buddy_userstatus_len+buddy_userlistenport_len+buddy_userip_len+sizeof(BUDDYLISTREPLYHRD))  // 读取的包长度不对
        return;
    
    char *userId = (char *)reply + sizeof(BUDDYLISTREPLYHRD);
    NSData *userIdData = [[NSData alloc] initWithBytes:userId length:buddy_userid_len];
    NSArray *buddyListUserId = [NSKeyedUnarchiver unarchiveObjectWithData:userIdData];
    
    char *userName = (char *)reply + sizeof(BUDDYLISTREPLYHRD) + buddy_userid_len;
    NSData *userNameData = [[NSData alloc] initWithBytes:userName length:buddy_username_len];
    NSArray *buddyListUserName = [NSKeyedUnarchiver unarchiveObjectWithData:userNameData];
    
    char *userImage = (char *)reply + sizeof(BUDDYLISTREPLYHRD) + buddy_userid_len + buddy_username_len;
    NSData *userImageData = [[NSData alloc] initWithBytes:userImage length:buddy_userimage_len];
    NSArray *buddyListUserImage = [NSKeyedUnarchiver unarchiveObjectWithData:userImageData];
    
    char *userStatus = (char *)reply + sizeof(BUDDYLISTREPLYHRD) + buddy_userid_len + buddy_username_len + buddy_userimage_len;
    NSData *userStatusData = [[NSData alloc] initWithBytes:userStatus length:buddy_userstatus_len];
    NSArray *buddyListUserStatus = [NSKeyedUnarchiver unarchiveObjectWithData:userStatusData];
    
    char *userListenPort = (char *)reply + sizeof(BUDDYLISTREPLYHRD) + buddy_userid_len + buddy_username_len + buddy_userimage_len + buddy_userstatus_len;
    NSData *userListenPortData = [[NSData alloc] initWithBytes:userListenPort length:buddy_userlistenport_len];
    NSArray *buddyListListenPort = [NSKeyedUnarchiver unarchiveObjectWithData:userListenPortData];
    
    char *userIp = (char *)reply + + sizeof(BUDDYLISTREPLYHRD) + buddy_userid_len + buddy_username_len + buddy_userimage_len + buddy_userstatus_len + buddy_userlistenport_len;
    NSData *userIpData = [[NSData alloc] initWithBytes:userIp length:buddy_userip_len];
    NSArray *buddyListIp = [NSKeyedUnarchiver unarchiveObjectWithData:userIpData];
    
    Buddy *buddy;
    BuddyGroup *firstBuddyGroup = [[BuddyGroup alloc] init];
    firstBuddyGroup->groupName = NSLocalizedString(@"好友列表", nil);
    for (NSInteger i=0; i<buddy_count; ++i)
    {
        buddy = [[Buddy alloc] init];
        buddy->buddyName = [buddyListUserName objectAtIndex:i];
        buddy->buddyQQ = [[buddyListUserId objectAtIndex:i] intValue];
        buddy->photo = [buddyListUserImage objectAtIndex:i];
        buddy->status = [[buddyListUserStatus objectAtIndex:i] intValue];
        buddy->listenPort = [[buddyListListenPort objectAtIndex:i] intValue];
        buddy->ip = [buddyListIp objectAtIndex:i];
        [firstBuddyGroup->buddyList addObject:buddy];
    }
    NSMutableArray *buddyGroupArray = [[[MainWindowController sharedMainWindowController] buddySource] buddyGroupArray];
    [buddyGroupArray removeAllObjects];
    [buddyGroupArray addObject:firstBuddyGroup];
    
    //当需要更新ui界面时，转回主线程，否则ui刷新会延迟
    dispatch_async(dispatch_get_main_queue(), ^{
        [[[MainWindowController sharedMainWindowController] buddyOutlineView] reloadData];
        [[NSNotificationCenter defaultCenter] postNotificationName:ReloadBuddyListNotification object:nil userInfo:nil];
    });
}

// 向服务器发送 BuddyList 拉取请求
- (void)onGetBuddyList
{
    Buddy *owner = [[MainWindowController sharedMainWindowController] myselfInfo];
    NSInteger qqNum = owner->buddyQQ;
    
    // 构造buddyList查询包头
    BUDDYLISTREQUESTHRD *buddyListRequest = (BUDDYLISTREQUESTHRD *)NewPtr(sizeof(BUDDYLISTREQUESTHRD));
    buddyListRequest->type = CMD_FUN_BUDDYLIST;
    buddyListRequest->operation = OP_BUDDY_LIST_REQUEST;
    buddyListRequest->qq_num = qqNum;
    //NSUInteger type = CMD_FUN_BUDDYLIST;
   // NSUInteger operation = OP_BUDDY_LIST_REQUEST;
    
    NSData *sendPacket = [[NSData alloc] initWithBytes:&(qqNum) length:sizeof(qqNum)];
    [[Connection sharedServerConnection] sendData:sendPacket cmd:buddyListRequest->type subcmd:buddyListRequest->operation];
   // [[Connection sharedServerConnection] sendData:sendPacket cmd:type subcmd:operation];
    NSLog(@"Send Buddy List Packet\n");
    DisposePtr((char *)buddyListRequest);
}

// 把 NSInteger 的qq号转换为 NSString 的
- (NSString *)convertQQNumToString:(NSInteger)qqNum
{
    NSMutableString *qqNumStr = [[NSMutableString alloc] initWithFormat:@"%ld", qqNum];
    while ([qqNumStr length] != QQ_NUM_LEN)
    {
        [qqNumStr insertString:@"0" atIndex:0];
    }
    return qqNumStr;
}

@end
